const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const db = require('../untils/database')
const jwt = require('jsonwebtoken')
const bcrypt = require('../untils/bcrypt')
// const { resolve, reject } = require('core-js/fn/promise')

const user = new Router()

user.use(bodyParser());

user.post('/register',async(ctx)=>{
    console.log(ctx.request.body);
    let userName = ctx.request.body.userName
    let password = ctx.request.body.password
    // console.log(password);
    // console.log(bcrypt.encrypt(password));
    // console.log(bcrypt.decrypt(password, bcrypt.encrypt(password)));
    let sql = `SELECT * FROM users WHERE user_name='${userName}'`;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        ctx.body = {
            user_name: userName,
            msg: '账号已存在',
        }    
    }else{
        const token = jwt.sign({ userName: userName, password: password }, 'secret', { expiresIn: 1296000 })
        let bcryptPassword = bcrypt.encrypt(password)
        let sql =`INSERT INTO users (user_name, password, token) values ('${userName}', '${bcryptPassword}', '${token}')`
        let result = await new Promise((resolve,reject)=>{
            return db.query(sql,(err,data)=>{
                if(err) throw err;
                let obj = {
                    token,
                    msg: '注册成功',
                    user_name: userName
                }
                resolve(obj)
            })   
        })
        if(result){
            ctx.body = result
        } 
    }  
})
        
user.post('/login',async(ctx)=>{
    let userName = ctx.request.body.userName
    let password = ctx.request.body.password
    let sql = `SELECT * FROM users WHERE user_name='${userName}'`;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){//找到帐号s
        console.log(result[0].password);
        console.log(password);
        if(result[0].password == password || bcrypt.decrypt(password, result[0].password)){
            ctx.body = {
                data: result[0],
                user_name: userName,
                msg: '登陆成功'
            }
        }else{
            ctx.body = {
                user_name: userName,
                msg: "密码错误"
            }
        }
    }else{
        ctx.body = {
            msg: "用户名不存在"
        }
    }
})

user.put('/changePassword',async(ctx)=>{
    let userId = ctx.request.body.userId
    let userName = ctx.request.body.userName
    let password = ctx.request.body.password
    let newPassword = ctx.request.body.newPassword
    let sql = `SELECT password FROM users WHERE id='${userId}'`;
    let result = await new Promise((resolve,reject)=>{
        return db.query(sql,(err,data)=>{
            if(err) throw err;
            if(data.length>0){
                resolve(data)
            }else{
                resolve(false)
            }
        })   
    })
    if(result){
        if(result[0].password == password  || bcrypt.decrypt(password, result[0].password)){
            const token = jwt.sign({ userName: userName, password: newPassword }, 'secret', { expiresIn: 1296000 })
            let newBcryptPassword = bcrypt.encrypt(newPassword)
            let sql = `UPDATE users SET password = '${newBcryptPassword}',token = '${token}'  WHERE id='${userId}'`;
            let result = await new Promise((resolve,reject)=>{
                return db.query(sql,(err,data)=>{
                    if(err) throw err;
                    let obj = {
                        token,
                        user_name: userName,
                        msg: '修改成功',
                    }
                    resolve(obj)
                })   
            })
            if(result){
                ctx.body = result
            }
        }else{
            ctx.body = {
                data: [],
                msg: "输入密码错误"
            }
        }
    } 
    
})


module.exports = user;